var server = "http://hoppin.cn:3000";
var zqid = 309621600; //张祺的网易云ID
var id = window.localStorage.getItem("wyy_id");
var qrkey;
var qrTime;
var login = false; //登录状态
var popup = document.getElementById("popup_login");
var popup_user = document.getElementById("popup_user");

$(document).ready(function () {
    $('button.btn-comment-open').click(function () {
        $('.comment-screen').addClass("active");
    });
    $('button.btn-comment-close').click(function () {
        $('.comment-screen').removeClass("active");
    });
    $('button.btn-extend').click(function () {
        $('.player-screen').addClass("active");
    });
    $('button.btn-open-music').click(function () {
        $('.player-screen').removeClass("active");
    });
    checkLoginState();
    loadAlbum();
    let query = window.location.search.substring(1);
    let vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        if (pair[0] == "s") {
            let search = reomveJing(pair[1]);
            $(".music-search").val(window.decodeURIComponent(search));
            searchMusic(search, true);
        }
    }
});

function reomveJing(str) {
    return str.lastIndexOf("#") == str.length - 1 ? str.substring(0, str.length - 1) : str;
}

function loadAlbum() {
    if (id) {
        $.get(`${server}/user/playlist?uid=${id}`, function (data) {
            if (data.code == 200) {
                loadPlayAlbumList(data.playlist);
            } else {
                alert("读取歌单失败，使用默认歌单")
                loadPlayAlbumList();
            }
        })
    }
}

function openLoginPopup() {
    popup.classList.add("open-popup");
}

function closeLoginPopup() {
    popup.classList.remove("open-popup");
}

/**
 * 登出
 */
function logout() {
    $.get(`${server}/logout?cookie=${encodeURIComponent(window.localStorage.getItem("cookie"))}`);
    cleanCache();
    location.reload()
}

function cleanCache() {
    window.localStorage.removeItem("wyy_id");
    window.localStorage.removeItem("cookie");
}

function loadQr() {
    if (!login) {
        $.get(`${server}/login/qr/key?timerstamp=${Date.now()}`, function (response) {
            if (response && response.code == 200 && response.data.code == 200) {
                qrkey = response.data.unikey;
                $.get(`${server}/login/qr/create?key=${qrkey}&qrimg=true&timerstamp=${Date.now()}`, function (responseQr) {
                    if (responseQr.code == 200) {
                        let qrimg = responseQr.data.qrimg;
                        $("#qr_img").attr("src", qrimg);
                        checkQr();
                    }
                })
            }
        })
    }
}

function checkQr() {
    if (qrTime) {
        clearInterval(qrTime);
    }
    qrTime = setInterval(function () {
        $.get(`${server}/login/qr/check?key=${qrkey}&timerstamp=${Date.now()}`, function (response) {
            //801等待扫描
            if (response.code === 800) {
                loadQr();
            }
            if (response.code === 803) {
                checkState2(response);
                // 这一步会返回cookie
                $("#waitGetState").click();
                clearInterval(qrTime);
                localStorage.setItem('cookie', response.cookie);
            }
        })
    }, 3000);
}

/**
 * 用户没有的情况
 */
function noUser() {
    $(".user-detail").html("").append2(`<p class="title user-login" style="margin-top: 20px;">请先 登录</p>`, function () {
        $(".user-login").off("click").on("click", function () {
            openLoginPopup();
            loadQr();
            $(this).off("click").on("click", function () {
                openLoginPopup();
            })
        })
    })
    // $(".artist").css("background-image",`url("https://hoppinzq.com/zui/static/picture/0.jpg")`)
    // $(".cover").css("background-image",`url("https://hoppinzq.com/static/images/logo/1640338711_113639.png")`);
}

/**
 * 获取用户详情
 */
function getUserDetail(uid) {
    $.get(`${server}/user/detail?uid=${uid}`, function (data) {
        console.log(data)
    })
}

/**
 * 检查登录状态
 */
function checkLoginState() {
    $.ajax({
        url: `${server}/login/status?cookie=${encodeURIComponent(window.localStorage.getItem("cookie"))}`,
        type: "get",
        success: function (data) {
            let _data = data.data;
            if (_data.code == 200 && _data.profile != null) {
                localStorage.setItem('wyy_id', _data.account.id);
                login = true;
                let user = _data.profile;
                $(".user-detail").html("").append2(`<p class="title user-name">欢迎您 ${user.nickname}</p><a class="title user-logout">登出</a>`, function () {
                    $(".user-logout").off("click").on("click", function () {
                        logout();
                    })
                })
                $(".artist").css("background-image", `url("${user.avatarUrl}")`)
                $(".cover").css("background-image", `url("${user.backgroundUrl}")`);
                $(".cover").css("filter", `brightness(90%)`);
            } else {
                login = false;
                noUser();
            }
        },
        error: function (data) {
            cleanCache();
            noUser();
            login = false;
            console.log(data.responseJSON);
        }
    })
}

function checkState2(response) {
    $("#wyy_tips").html("授权登录成功，正在检查登录状态...");

    $.ajax({
        url: `${server}/login/status?timerstamp=${Date.now()}`,
        type: "post",
        data: {
            cookie: response.cookie
        },
        beforeSend: function () {
            $("#wyy_tips").html("授权登录成功，正在检查登录状态...");
        },
        success: function (response) {
            if (response.data.account.status >= 0) {
                localStorage.setItem('wyy_id', response.data.account.id);
                setTimeout(function () {
                    $("#wyy_tips").html("检查登录状态完成，即将重新渲染页面");
                    checkLoginState();
                    setTimeout(function () {
                        closeLoginPopup();
                    }, 1000)
                }, 2000)
            } else {
                $("#wyy_tips").html("检查登录状态异常,请用其他方式登录");
            }

        },
        error: function () {
            $("#wyy_tips").html("检查登录状态异常,请用其他方式登录");
        }
    })
}
